<template>
  <div class="container">
    <div class="app-container">
      <el-tree
        :data="depts"
        :props="defaultProps"
        default-expand-all
        :expand-on-click-node="false"
      >
        <template v-slot="{ data }">
          <el-row
            type="flex"
            justify="space-between"
            align="middle"
            style="width: 100%; height: 30px"
          >
            <el-col>{{ data.name }}</el-col>
            <!-- <el-col>管理员</el-col> -->
            <el-col :span="4">
              <span class="tree-manager">{{ data.managerName }}</span>
              <!-- 下拉菜单 -->
              <!-- $event，默认参数 -->
              <el-dropdown @command="operateDept($event, data.id)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除部门</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <!-- 这里我们同样使用了sync修饰符，可以监听子组件传过来的 update:属性名的事件，直接将父组件的值进行修改 -->
    <add-dept
      ref="addDept"
      :show-dialog.sync="showDialog"
      :current-id="currentId"
      @updateDepartment="getDepartment()"
    />
    <!-- 新增成功再重新拉取数据渲染 -->
  </div>
</template>
<script>
import { getDepartment, deleteDepartment } from '@/api/department'
import { transListToTreeData } from '@/utils'
import AddDept from './components/add-dept.vue'

export default {
  name: 'Department',
  components: { AddDept },
  data() {
    return {
      currentId: null,
      showDialog: false,
      depts: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },

  created() {
    this.getDepartment()
  },
  methods: {
    async getDepartment() {
      // 调用接口方法 并转换数据结构
      this.depts = transListToTreeData(await getDepartment(), 0)
    },
    async operateDept(type, id) {
      if (type === 'add') {
        this.showDialog = true
        this.currentId = id
      } else if (type === 'edit') {
        // 调用子组件方法
        // this.$refs.addDept.getDepartmentDetail(id);
        this.currentId = id
        this.$nextTick(async() => {
          await this.$refs.addDept.getDepartmentDetail(this.currentId)
          this.showDialog = true
        })
      } else {
        await this.$confirm('确定删除？')
        await deleteDepartment(id)
        this.getDepartment()
        this.$message.success('删除成功')
      }
    }
  }
}
</script>
<style scoped>
.tree-manager {
  display: inline-block;
  width: 50px;
  margin-right: 15px;
}
</style>
